import type { RouteRecordRaw } from "vue-router";

export const loadLocalRoutes = () => {
  // 动态添加路由
  const localRoutes: RouteRecordRaw[] = [];
  // 获取本地路由文件
  const files: Record<string, any> = import.meta.glob("@/router/main/**/*.ts", {
    eager: true /*立刻获取文件信息，而不是懒加载获取*/
  });
  for (const path in files) {
    const module = files[path];
    localRoutes.push(module.default);
  }
  return localRoutes;
};

export let firstMenu: any = null;

/**
 * 将用户菜单转换为路由
 */
export const mapMenus = (userMenus: any[]) => {
  const localRoutes = loadLocalRoutes();
  const routes: RouteRecordRaw[] = [];
  // 根据菜单信息匹配该用户权限下的路由
  for (const menuItem of userMenus) {
    if (menuItem.children) {
      for (const submenu of menuItem.children) {
        const route = localRoutes.find((route) => route.path === submenu.url);
        if (route) {
          // 给父级菜单添加重定向
          if (!routes.find((r) => r.path === menuItem.url)) {
            routes.push({ path: menuItem.url, redirect: route.path });
          }
          // 添加二级菜单
          routes.push(route);
        }
        if (!firstMenu && route) {
          firstMenu = submenu;
          // console.log("=>(mapMenus.ts:35) firstMenu", firstMenu);
        }
      }
    }
  }
  return routes;
};

/**
 * 根据路径找到对应的菜单
 * @param path
 * @param userMenus
 */
export function mapPathToMenu(path: string, userMenus: any[]) {
  for (const menu of userMenus) {
    for (const submenu of menu.children) {
      if (submenu.url === path) {
        return submenu;
      }
    }
  }
}

/**
 * 根据路径找到对应的面包屑
 * @param path
 * @param userMenus
 */
export function mapPathToBreadcrumbs(path: string, userMenus: any[]) {
  const breadcrumbs: any[] = [];
  for (const menu of userMenus) {
    for (const submenu of menu.children) {
      if (submenu.url === path) {
        breadcrumbs.push({ name: menu.name, path: menu.url });
        breadcrumbs.push({ name: submenu.name, path: submenu.url });
      }
    }
  }
  return breadcrumbs;
}

/**
 * 将菜单列表转换为菜单id列表
 * @param menuList 菜单列表
 */
export function mapMenuListToIds(menuList: any[]) {
  const ids: number[] = [];
  function recurseGetIds(menus: any[]) {
    for (const menu of menus) {
      if (menu.children) {
        recurseGetIds(menu.children)
      } else {
        ids.push(menu.id)
      }
    }
  }
  recurseGetIds(menuList)
  return ids;
}

/**
 * 从菜单列表中获取按钮权限列表
 * @param menuList
 */
export function mapMenuListToPermission(menuList: any[]) {
  const permissions: string[] = [];
  function recurseGetPermission(menuList: any[]) {
    for (const menu of menuList) {
      if (menu.type === 1 || menu.type === 2) {
        recurseGetPermission(menu.children ?? [])
      } else {
        permissions.push(menu.permission)
      }
    }
  }
  recurseGetPermission(menuList);
  return permissions;
}
